iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
JavaScript

火箭通關JS30系列 第 7

JS30-07 - Array Cardio Day 2

  • 分享至 

  • xImage
  •  

課程目的:

這次的內容是JavaScript 陣列操作的幾個常見方法,特別是針對物件陣列的操作, some()every()find()findIndex() 四種方法,接下來我們就來實際操作
作品實做

本次功能實作重點:

  • 檢查是否有至少一個人滿 19 歲 (some())
  • 檢查是否全部人滿 19 歲 (some())
  • 尋找特定ID (find())
  • 尋找特定ID的index(findIndex()

範例資料:

   const people = [
        { name: "Wes", year: 1988 },
        { name: "Kait", year: 1986 },
        { name: "Irv", year: 1970 },
        { name: "Lux", year: 2015 },
      ];

      const comments = [
        { text: "Love this!", id: 523423 },
        { text: "Super good", id: 823423 },
        { text: "You are the best", id: 2039842 },
        { text: "Ramen is my fav food ever", id: 123523 },
        { text: "Nice Nice Nice!", id: 542328 },
      ];

檢查是否有至少一個人滿 19 歲 (some())

      const isAdult = people.some(
        (e) => new Date().getFullYear() - e.year >= 19
      );
      console.log({ isAdult });

some() 用來遍歷arr中的所有元素,當有一個元素通過檢測則會回傳布林值(true)

new Date().getFullYear() 函式為取得當下年份,減掉e.year ≥19(判斷是否滿19)

檢查是否全部人滿 19 歲 (some())

const everyIsAdult = people.every(
        (e) => new Date().getFullYear() - e.year >= 19
      );
      console.log({ everyIsAdult });

every() 用來遍歷arr中的所有元素,當有全部元素通過檢測則會回傳布林值(true)

尋找特定ID (find())

let findID = comments.find((e) => e.id === 823423);
      console.log({ findID });

find() 會回傳第一個滿足所提供之測試函式的元素值

e.id === 823423 我們查找的條件是Id值符合823423則回傳元素

尋找特定ID的index(findIndex()

 let findIndex = comments.findIndex((e) => e.id === 823423);
      console.log(findIndex); 

findIndex() 會回傳第一個滿足所提供之測試函式的元素值之Index,如果沒有符合的對象,將返回 -1 。

e.id === 823423 我們查找的條件是Id值符合823423則回傳元素index

導讀文件以及學習資源

JS30


上一篇
JS30-06-Type Ahead
下一篇
JS30-08 - Fun with HTML5 Canvas
系列文
火箭通關JS3014
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言